import React from 'react'
import Admin from "../../../layout/Admin";
import MallModel from "../../../model/mall";
import {Button, Form, Input, InputNumber, Modal, Popconfirm, Popover, Radio, Table, Upload,} from "antd";
import PaginationFooter from "../../../component/PaginationFooter/PaginationFooter";
import {formLayout, formTailLayout} from "../../operation/vote/vote";
import { UploadOutlined, InboxOutlined, CloseCircleOutlined, } from '@ant-design/icons';
import Info from "../../../service/info";
const noticeDefaultValue = '重要说明\n' +
    '1.商品以收到的实物为准图片仅供参考;\n' +
    '2.应豆商城的商品,每件商品每个用户每月可兑换多件,若发现多个用户账号使用相同手机号或收货地址兑换同一商品，则自动取消订单,被扣除的应豆不退还;\n' +
    '3.除商品本身不能正常兑换外,商品一经兑换,一律不退还应豆,请用户兑换前阅读使用规则、使用说明、有效期等重要信息;\n' +
    '4.实物商品包邮,不含港澳台地区以及部分偏远地区(具体可询问客服，若不包邮商品须支付邮费，否则不予寄出)\n' +
    '5.若您兑换的礼品有不同的规格型号,请在填写信息中进行备注,否则不予发货;若缺货，等货源充足后寄出。\n' +
    '6、兑换虚拟商品,请留下您的联系方式, 并保持设备通畅。\n' +
    '7.若存在恶意刷分等作弊行为,小应体育有权扣除所有奖励;\n' +
    '8.通过非法途径获得应豆后进行的正常兑换行为,或不按商品使用规则进行兑换,商家有权不提供服务;\n' +
    '9.凡以不正当手段(包括但不限于作弊、扰乱系统、实施网络攻击等)进行兑换,平台有权终止当次兑换，并将违法所得清零。\n' +
    '10.兑换奖品如有疑问请加客服微信公众号:一球必应；'

export function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

const log = console.log.bind(console)

class Mall extends React.Component {
    constructor(props) {
        super(props)
        this.model = new MallModel()
        this.state = {
            list: [],
            hot: [],
            image: [],
            p: 0,
            previewImage: '',
            previewTitle: '',
            editValue: null,
            edit: false,
            modal: {
                add: false,
                preview: false,
                previewImages: false,
            },
            previewImages: [],
            hotChecked: false,
        }
        this.itemTypes = {
            1: '手机充值',
            2: '商品',
            3: '道具',
        }
        this.columns = [
            // Id: 1
            {
                title: 'Id',
                dataIndex: 'Id',
            },
            // Style: 2
            {
                title: '类型',
                dataIndex: 'Style',
                render: (style) => this.itemTypes[style],
            },
            // Propid: 0
            {
                title: '道具编号',
                dataIndex: 'Propid',
            },
            // Name: "123"
            {
                title: '品名',
                dataIndex: 'Name',
            },
            // Buynum: 0
            {
                title: '兑换次数',
                dataIndex: 'Buynum',
            },
            // Oldprice: 123
            // Price: 123
            {
                title: '价格',
                render: (record) => {
                    return <span>原价：{record.Oldprice} 现价：{record.Price}</span>
                }
            },
            {
                title: '是否缺货',
                dataIndex: 'Quehuo',
                render: (text) => {
                    return text === 0 ? '否' : '是'
                }
            },

            {
                title: '热门',
                dataIndex: 'Hot',
                render: (text, record) => {
                    return text === 0
                        ? <a onClick={() => this.setHot({Id: record.Id, Hot: 1,})}>设置为热门</a>
                        : <a onClick={() => this.setHot({Id: record.Id, Hot: 0,})}>取消热门</a>
                }
            },
            // Notice: "123"
            {
                title: '说明',
                dataIndex: 'Notice',
                render: (text) => <Popover content={text} title='商品说明'>
                    <Button>说明</Button>
                </Popover>,
            },
            // Detail: "123"
            {
                title: '详情',
                dataIndex: 'Detail',
                render: (text) => <Popover content={text} title='商品详情'>
                    <Button>详情</Button>
                </Popover>,
            },
            // Image: ["https://youtoball.oss-cn-shenzhen.aliyuncs.com/product/20210310092358.1.jpg"]
            {
                title: '操作',
                render: (record) => {
                    return <div className='action-links'>
                        <a onClick={() => this.onImagesPreview(record)}>查看图片</a>
                        <Popconfirm title={'确认删除？'}
                                    onConfirm={() => this.delete(record)}
                        >
                            <a >删除</a>
                        </Popconfirm>
                        <a onClick={() => this.callEdit(record)}>编辑</a>
                    </div>
                }
            }
            // Pos: 0

        ]
    }

    componentDidMount() {
        this.all()
    }

    all = () => {
        const params = {
            p: this.state.p,
        }
        this.model
            .all(params)
            .then(res => {
                const list = res.data.ok
                this.setState({
                    list,
                })
            })
    }

    hot = () => {
        this.model
            .hot()
            .then(res => {
                const list = res.data.ok
                this.setState({
                    list,
                })
            })
    }

    setHot = (params) => {
        this.model
            .setHot(params)
            .then(res => {
                if (res.data.ok) {
                    if (this.state.hot) {
                        this.hot()
                    } else {
                        this.all()
                    }
                }
            })
    }

    delete = (record) => {
        log(record)
        this.model
            .add({
                name: 'del',
                id: record.Id,
                image: record.Image,
            })
            .then(res => {
                if (res.data.ok) {
                    Info.success('删除成功')
                }
                this.all()
            })
    }

    onAdd = (value) => {
        value.image = this.state.image
        if (this.state.edit) {
            value.id = this.state.editValue.Id
            value.image = [...this.state.editValue.Image, ...this.state.image,]
        }
        log(value)
        this.model.add(value)
            .then(res => {
                if (res.data.ok === 1) {
                    Info.success('上传商品成功')
                    this.addForm.resetFields()
                    this.cancelModal('add')
                    this.setState({
                        image: [],
                        edit: false,
                    })
                    this.all()
                } else {
                    Info.warning('上传失败')
                }
            })
    }

    callEdit = (record) => {

        this.callModal('add')
        this.setState({
            editValue: record,
            edit: true,
        })

        setTimeout(() => {
            this.addForm.setFieldsValue({
                detail: record.Detail,
                name: record.Name,
                style: record.Style,
                price: record.Price,
                oldprice: record.Oldprice,
                notice: record.Notice,
                pos: record.Pos,
                quehuo: record.Quehuo,
            })
        }, 0)
    }

    prevPage = () => {
        this.setState({
            p: this.state.p - 1,
        }, () => this.all())
    }

    nextPage = () => {
        this.setState({
            p: this.state.p + 1,
        }, () => this.all())
    }

    callModal(key) {
        this.setState({
            ...this.state,
            modal: {
                ...this.state.modal,
                [key]: true,
            }
        })
    }

    cancelModal(key) {
        this.setState({
            ...this.state,
            modal: {
                ...this.state.modal,
                [key]: false
            }
        })
    }

    onImagesPreview = (item) => {
        // log(item)
        this.setState({
            previewImages: item.Image,
        }, () => this.callModal('previewImages'))
    }

    uploadInputProps = (name) => {

        const fileList = this.state[name]

        return {

            onRemove: file => {
                this.setState(state => {
                    const index = state[name].indexOf(file);
                    const newFileList = state[name].slice();
                    newFileList.splice(index, 1);
                    return {
                        [name]: newFileList,
                    }
                })
            },

            beforeUpload: () => false,

            onChange: ({fileList,}) => {
                this.setState({
                    [name]: fileList,
                })
            },

            onPreview: async (file) => {
                if (!file.url && !file.preview) {
                    file.preview = await getBase64(file.originFileObj);
                }

                this.setState({
                    previewImage: file.url || file.preview,
                    previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
                }, () => this.callModal('preview'));
            },

            fileList,
        }

    }

    onAddFormCancel = () => {
        this.cancelModal('add')
        this.addForm.resetFields()
        this.setState({
            edit: false,
            image: [],
        })
    }

    deleteEditImage = (index) => {
        const imgs = this.state.editValue.Image
        imgs.splice(index, 1)
        this.setState({
            editValue: {
                ...this.state.editValue,
                Image: imgs,
            }
        })
    }

    render() {

        return <>
            <Modal
                visible={this.state.modal.previewImages}
                title='商品图'
                footer={null}
                onCancel={() => this.cancelModal('previewImages')}
            >
                {this.state.previewImages.map((src, index) => <img alt='' style={{width: '200px'}} src={src} key={index}/>)}
            </Modal>
            <Modal
                visible={this.state.modal.preview}
                title={this.state.previewTitle}
                footer={null}
                onCancel={() => this.cancelModal('preview')}
            >
                <img alt="example" style={{ width: '100%' }} src={this.state.previewImage} />
            </Modal>
            <Modal
                visible={this.state.modal.add}
                onCancel={() => this.onAddFormCancel()}
                footer={null}
                title='添加商品'
                width='80%'
            >
                <Form
                    {...formLayout}
                    name='add'
                    ref={el => this.addForm = el}
                    onFinish={this.onAdd}
                    initialValues={{
                        pos: 1,
                        notice: noticeDefaultValue,
                    }}
                >
                    {/*id//0插入新的，不为0更新或删除*/}
                    {/*name//商品名，当填“del”表示删除*/}
                    <Form.Item
                        label="商品名称"
                        name="name"
                        rules={[
                            {
                                required: true,
                                message: '请输入商品名称',
                            },
                        ]}
                    >
                        <Input placeholder='请输入商品名称'/>
                    </Form.Item>
                    {/*price//现价*/}
                    <Form.Item
                        label="商品价格"
                        name="price"
                        rules={[
                            {
                                required: true,
                                message: '请输入商品价格',
                            },
                        ]}
                    >
                        <InputNumber placeholder='请输入商品价格'/>
                    </Form.Item>
                    {/*oldpric//原价*/}
                    <Form.Item
                        label="商品原价"
                        name="oldprice"
                        rules={[
                            {
                                required: true,
                                message: '请输入商品原价',
                            },
                        ]}
                    >
                        <InputNumber placeholder='请输入商品原价'/>
                    </Form.Item>
                    {/*detail//商品详情*/}
                    <Form.Item
                        label="商品详情"
                        name="detail"
                        rules={[
                            {
                                required: true,
                                message: '请输入商品详情',
                            },
                        ]}
                    >
                        <Input placeholder='请输入商品详情'/>
                    </Form.Item>
                    {/*notice//商品说明*/}
                    <Form.Item
                        label="商品说明"
                        name="notice"
                        rules={[
                            {
                                required: true,
                                message: '请输入商品说明',
                            },
                        ]}
                    >
                        <Input.TextArea placeholder='请输入商品说明'/>
                    </Form.Item>

                    {/*style//物品类型（1手机充值，2商品，3道具）*/}
                    <Form.Item
                        name="style"
                        label="物品类型"
                        rules={[
                            {
                                required: true,
                                message: '请选择物品类型',
                            },
                        ]}
                    >
                        <Radio.Group>
                            <Radio value={1}>手机充值</Radio>
                            <Radio value={2}>商品</Radio>
                            <Radio value={3}>道具</Radio>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item
                        name="quehuo"
                        label="是否缺货"
                        rules={[
                            {
                                required: true,
                                message: '请选择是否缺货',
                            },
                        ]}
                    >
                        <Radio.Group>
                            <Radio value={0}>否</Radio>
                            <Radio value={1}>是</Radio>
                        </Radio.Group>
                    </Form.Item>

                    {/*pos//位置*/}
                    <Form.Item
                        label="商品顺序"
                        name="pos"
                        rules={[
                            {
                                required: true,
                                message: '输入商品在列表中的位置',
                            },
                        ]}
                    >
                        <InputNumber placeholder='可输入商品在列表中的位置'/>
                    </Form.Item>
                    {/*propid//当商品为道具时，写入道具id*/}
                    <Form.Item
                        label="道具id"
                        name="propid"
                    >
                        <Input placeholder='如果为道具请输入道具ID'/>
                    </Form.Item>


                    {/*image//图片数组*/}

                    {this.state.edit && <Form.Item
                        label='现有图片'
                    >
                        {this.state.editValue.Image.map((src, index) => {
                            return <div
                                key={index}
                                style={{position: 'relative', display: 'inline-block'}}
                            >
                                <img src={src} alt='' style={{width: 200}}/>
                                <CloseCircleOutlined
                                    style={{position: 'absolute', top: 0, right: 0,}}
                                    onClick={() => {
                                        this.deleteEditImage(index)
                                    }}
                                />
                            </div>
                        })}
                    </Form.Item>}
                    <Form.Item
                        label="上传图片"
                    >
                        <Upload
                            listType="picture-card"
                            fileList={this.state.image}
                            {...this.uploadInputProps('image')}
                            multiple={true}
                        >
                            <Button icon={<UploadOutlined />}>Click to upload</Button>
                        </Upload>
                    </Form.Item>
                    <Form.Item {...formTailLayout}>

                        <Button type="primary" htmlType="submit">
                            Submit
                        </Button>

                    </Form.Item>
                </Form>

            </Modal>

            <Admin>
                <div className='list-container'>
                    <div style={{marginBottom: 8,}}>
                        <Button onClick={() => this.callModal('add')}>
                            添加商品
                        </Button>
                    </div>
                    <div style={{marginBottom: 8,}}>
                        <Radio.Group
                            value={this.state.hotChecked}
                            onChange={(e) => {
                                const checked = e.target.value
                                log(checked)
                                this.setState({
                                    hotChecked: checked,
                                    p: 0,
                                }, () => {
                                    if (checked) {
                                        this.hot()
                                    } else {
                                        this.all()
                                    }
                                })
                            }}
                        >
                            <Radio value={false}>所有</Radio>
                            <Radio value={true}>热门</Radio>
                        </Radio.Group>
                    </div>
                    <Table
                        dataSource={this.state.list}
                        columns={this.columns}
                        pagination={false}
                        rowKey={(record, index) => index}
                    />

                    {this.state.hotChecked === false && <PaginationFooter
                        pageIndex={this.state.p}
                        prevPage={this.prevPage}
                        nextPage={this.nextPage}
                    />}
                </div>
            </Admin>
        </>
    }
}

export default Mall